package admin

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"gitee.com/jikey/elk-blog/setting"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"strconv"
)

type Comment struct {
	Base
}

func (m *Comment) Index(c *gin.Context) {
	data := make(map[string]interface{})
	response.HTML(c, "comment/index", data)
}

// List 列表
func (m *Comment) List(c *gin.Context) {
	data := map[string]interface{}{
		"rows":  []Comment{},
		"total": 0,
	}

	pageNum, _ := strconv.Atoi(c.Query("page"))

	title := c.Query("content")
	maps := "pid = 0"

	if len(title) > 0 {
		maps += " and content like '%" + title + "%'"
	}

	list := service.Comment.List(pageNum, setting.PageSize, maps)
	data["rows"] = list
	data["total"] = service.Comment.Total(maps)

	response.Success(c, data)
}

// Insert 新增保存
func (m *Comment) Insert(c *gin.Context) {
	comment := &model.Comment{}

	if err := c.ShouldBind(&comment); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	err := service.Comment.Create(comment)

	if err != nil {
		logrus.Error("新增失败", err)
		response.Fail(c, e.ErrorInsert)
		return
	}

	response.Success(c, comment)
}

// Destory 删除
func (m *Comment) Destory(c *gin.Context) {
	id := c.PostForm("id")
	service.Comment.Delete(id)

	response.Success(c, id)
}
